<template>
    <!--查询条件-->
    <el-card>
        <el-form ref="postRef" :inline="true" :model="queryParams" label-width="68px">
            <el-form-item label="用户id" prop="userId">
                <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable style="width: 240px;"/>
            </el-form-item>
            <el-form-item label="用户名" prop="nick_name">
                <el-input v-model="queryParams.nick_name" placeholder="请输入用户名称" clearable style="width: 240px;"/>
            </el-form-item>
            <!--搜索按钮-->
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery()">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>

    <!--表格 结果展示-->
    <el-card style="margin-top: 20px;">

        <template #header>
            <el-row :gutter="10">
                <!-- <el-col :span="1.5">
                    <el-button v-hasPermi="['system:post:add']" type="primary" plain icon="Plus"
                        @click="handleAdd">新增</el-button>
                </el-col> -->
                <el-col :span="1.5">
                    <el-button v-hasPermi="['my:post:edit']" type="success" plain icon="Edit" :disabled="single"
                        @click="handleUpdate()">修改</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button v-hasPermi="['my:post:remove']" type="danger" plain icon="Delete"
                        :disabled="multiple" @click="handleDelete()">删除</el-button>
                </el-col>
               <!-- <el-col :span="1.5">
                    <el-button v-hasPermi="['my:post:export']" type="warning" plain icon="Download"
                        @click="handleExport">导出</el-button>
                </el-col> -->
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>


            <el-table v-loading="loading" :data="pageData.rows" style="width: 100%"
                @selectionChange="handleSelectionChange">
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column label="用户id" align="center" prop="userId" />
                <el-table-column label="用户名称" align="center" prop="nickName" :show-overflow-tooltip="true" />
                <el-table-column label="用户头像" align="center" >
                    <template #default="scope">
                         <img :src="scope.row.avatar" width="150"/>
                    </template>
                </el-table-column>
                <el-table-column label="用户签名" align="center" prop="sign" :show-overflow-tooltip="true" />
                <!--<el-table-column label="用户性别" align="center" prop="sex" :show-overflow-tooltip="true" />-->
               <el-table-column prop="sex" label="性别" show-overflow-tooltip >
                           <template #default="scope">
                                <el-tag v-if="scope.row.sex==0">男</el-tag>
                                <el-tag type="danger" v-else-if="scope.row.sex==1">女</el-tag>
                           </template>
                 </el-table-column>
                <el-table-column label="粉丝数" align="center" prop="fans" :show-overflow-tooltip="true" />
                <el-table-column label="关注数" align="center" prop="followers" :show-overflow-tooltip="true" />
                <el-table-column label="获赞数" align="center" prop="likes" :show-overflow-tooltip="true" />
                <el-table-column label="用户主页背景图片" align="center" >
                    <template #default="scope">
                        <img :src="scope.row.homeimage" width="150"/>
                    </template>
                </el-table-column>
                <el-table-column label="用户状态" align="center" prop="status">
                    <template #default="scope">
                       <el-tag   v-if="scope.row.status==0">正常</el-tag>
                       <el-tag v-else-if="scope.row.status==1" type="danger">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                    <template #default="scope">
                        <span>{{parseTime(scope.row.createTime)}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button v-hasPermi="['my:post:edit']" circle type="primary" icon="Edit"
                            @click="handleUpdate(scope.row)" />
                        <el-button v-hasPermi="['my:post:remove']" circle type="danger" icon="Delete"
                            @click="handleDelete(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="pageData.total > 0" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" :total="pageData.total" @pagination="getList" />
        </template>
    </el-card>
 <!-- 新增修改对话框  -->
        <el-dialog v-model="open" :title="title" width="500" :close-on-click-modal="false">
            <el-form ref="editRef" :model="form" label-width="80px">
                <el-form-item label="用户姓名" prop="nickName"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-input v-model="form.nickName" placeholder="请输入用户姓名" />
                </el-form-item>

                <el-form-item label="用户头像" prop="avatar">
                    <div class='imageDiv'>
                        <el-image
                        style="width: 100px; height: 100px; object-fit: cover;"
                        :src="imageUrl"

                      />
                     <el-button
                        style="background-color: red;"
                        type="text"
                        icon="el-icon-delete"
                        size="mini"
                        @click="handleRemove()"
                      />
                    </div>

                     <el-upload
                        class="avatar-uploader"
                        :data="imageData.ossdata"
                        :action="uploadUrl"
                        name="imgFile"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                      >

                        <el-icon  class="avatar-uploader-icon"><Plus /></el-icon>
                      </el-upload>
                </el-form-item>

                <el-form-item label="用户签名" prop="sign">
                    <el-input v-model="form.sign" placeholder="请输入用户签名" />
                </el-form-item>

               <!-- <el-form-item label="状态" prop="status"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_normal_disable" :key="dict.value"
                            :label="dict.value">{{dict.label}}</el-radio>
                    </el-radio-group>
                </el-form-item> -->
               <el-form-item label="用户背景图片" prop="homeimage">
                   <div class='imageDiv'>
                       <el-image
                       style="width: 100px; height: 100px; object-fit: cover;"
                       :src="imageUrlBack"

                     />
                    <el-button
                       style="background-color: red;"
                       type="text"
                       icon="el-icon-delete"
                       size="mini"
                       @click="handleRemoveBack()"
                     />
                   </div>

                    <el-upload
                       class="avatar-uploader"
                       :data="imageData.ossdata"
                       :action="uploadUrl"
                       name="imgFile"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccessBack"
                       :before-upload="beforeAvatarUpload"
                     >

                       <el-icon  class="avatar-uploader-icon"><Plus /></el-icon>
                     </el-upload>
               </el-form-item>
                <el-form-item label="用户性别" prop="remark">
                   <!-- <el-input v-model="form.sex" type="textarea" placeholder="请选择用户性别" /> -->
                   <el-radio-group v-model="form.sex">
                       <el-radio :label="0" >男</el-radio>
                       <el-radio :label="1" >女</el-radio>
                   </el-radio-group>
                </el-form-item>
                <el-form-item label="用户状态" prop="remark">
                  <el-radio-group v-model="form.status">
                      <el-radio :label="0" >正常</el-radio>
                      <el-radio :label="1" >停用</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

</template>

<script setup name="Post" lang="ts">
    import {ref,reactive,toRefs, getCurrentInstance, ComponentInternalInstance} from 'vue';
    import {appMyPostReq,appMyResp,appMyReqEdit} from '@/types/app/my'
    import {post,postinformation,editpost} from '@/api/app/my/type'
    import type { FormInstance } from 'element-plus';
    import { ElMessage, imageEmits } from 'element-plus'
    import { Plus } from '@element-plus/icons-vue'
    // import type { UploadProps } from 'element-plu'

    const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API+'/oss/uploadImg'); // 替换为你的实际上传 URL

    const imageUrl = ref('')
    const imageUrlBack = ref('')

    //自己的定义额外参数
    const imageData = reactive({
        ossdata: {
            fatherPath:'images'
        }
    });

    // 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;

    //响应式对象(是否显示加载界面)
    const loading = ref<boolean>(false);

    // 编辑按钮 默认不启用
    const single = ref<boolean>(true);
    //删除按钮 默认不启用
    const multiple = ref<boolean>(true);
    const showSearch = ref<boolean>(true);

    // 表格选中项
    const mutilSelection = ref<appMyResp[]>([]);
    // 表格选中项 的主键
    const ids = ref<number[]>([]);

    // 对话框配置
    const open = ref(false);
    const title = ref('');

    // 表单验证对象
    const editRef = ref<FormInstance>();

    // 分页数据
    const pageData = reactive<{
        total : number;
        rows : appMyResp[]
    }>({
        total: 0,
        rows: []
    })

    // 响应式代理模型
    const data = reactive<{
        form : appMyReqEdit;
        queryParams : appMyPostReq;
    }>({
        form: {
            userId: undefined,
            nickName: '',
            avatar: '',
            sign: '',
            homeimage: '',
            sex: undefined,
            status:undefined,
        },
        queryParams: {
            userId:undefined,
            nick_name:'',
            pageNum: 1,
            pageSize: 10
        }
    })

    // 代理模型转为相应模型
    const { queryParams ,form} = toRefs(data)

    //重置
    function resetQuery(){
        proxy?.resetForm('postRef');
        //查询
        handleQuery();
    }

    //查询
    function handleQuery(){
        queryParams.value.pageNum=1;
        getList();
    }

    //分页查询
    function getList(){
        loading.value=true;
        console.log(queryParams.value)
        post(queryParams.value).then((resp:any)=>{
            pageData.total=resp.data.total;
            pageData.rows=resp.data.list;
            loading.value=false;
        })
    }
    // 多选框选中数据
    function handleSelectionChange(selection : appMyResp[]) {
        mutilSelection.value = selection;
        ids.value = selection.map(row => row.userId);
        // 修改按钮禁用值判断
        single.value = selection.length !== 1;
        // 删除按钮禁用值判断
        multiple.value = selection.length === 0;
    }

    // 修改
    function handleUpdate(row ?: null | appMyResp) {
        let primaryKey : number;
        if (row) {
            primaryKey = row.userId;
        } else {
            primaryKey = ids.value[0];
        }

        reset();

        // 从后台查询值是多少
        postinformation(primaryKey).then((resp : any) => {
            form.value = resp.data;
            title.value = '个人主页-修改';
            if(form.value.avatar){
                imageUrl.value=form.value.avatar
            }
            if(form.value.homeimage){
                imageUrlBack.value=form.value.homeimage
            }
            open.value = true;
        });
    }

    // // 删除 或 禁用
    // function handleDelete(row ?: appMyResp) {
    //     let primaryKeys : any;
    //     if (row) {
    //         primaryKeys = row.userId;
    //     } else {
    //         primaryKeys = ids.value;
    //     }

    //     proxy?.$modal
    //         .confirm('是否确认删除参数编号为"' + primaryKeys + '"的数据项？')
    //         .then(function () {
    //             return delPost(primaryKeys);
    //         })
    //         .then(() => {
    //             getList();
    //             proxy!.$modal.msgSuccess('删除成功');
    //         })
    //         .catch((e : any) => {
    //             console.log(e);
    //         });
    // }

    // 新增或修改 提交按钮
    async function submitForm() {
        if (!editRef.value) {
            return;
        }
        await editRef.value.validate((valid : boolean, fields : any) => {
            if (valid) {
                // 调用修改请求
                if (form.value.userId) {
                    if(imageUrl.value && imageUrlBack.value){
                         form.value.avatar=imageUrl.value
                         form.value.homeimage=imageUrlBack.value
                         editpost(form.value).then(() => {
                             proxy?.$modal.msgSuccess('修改成功');
                             open.value = false;
                             getList();
                         });
                    }else{
                          ElMessage.error('头像或背景图片不能为空');
                    }

                }
                // else {
                //     //调用新增请求
                //     addPost(form.value).then(() => {
                //         proxy?.$modal.msgSuccess('新增成功');
                //         open.value = false;
                //         getList();
                //     });
                // }

            } else {
                console.log('error submit!', fields);
            }
        });
    }

    // 新增或修改 对话框取消按钮
    function cancel() {
        open.value = false;
    }


    // 重置表单 值
    function reset() {
        form.value = {
            userId: undefined,
            nickName: '',
            avatar: '',
            sign: '',
            homeimage: '',
            sex: undefined,
            status:undefined,
        };
        imageUrl.value=''
        imageUrlBack.value=''
        // 重置表单 样式
        proxy?.resetForm('editRef');
    }


     getList();


// ---------------------------------------图片上传




// 处理头像上传成功
const handleAvatarSuccess = (res, file) => {
  imageUrl.value=res.data
  ElMessage.success('上传成功');
};

// 处理背景图片上传成功
const handleAvatarSuccessBack = (res, file) => {
  imageUrlBack.value=res.data
  ElMessage.success('上传成功');
};

// 处理图片删除
const handleRemove = () => {
  imageUrl.value=''
  // ElMessage.success('删除成功');
};

const handleRemoveBack=()=>{
    imageUrlBack.value=''
}


const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('上传文件只能是图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

</script>

<style>

    .avatar-uploader .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }



    .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
    .imageDiv {
      width:150px;
      height: 150px;
      display: flex;
      position: relative;
      justify-content: center;
      align-items: center;
    }
</style>
